<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color: tomato;
    }
  </style>
</head>

<body>
  <div id="app">
    <div id="navs">
      <router-link to="/home" tag="button">
        home页
      </router-link>
      <router-link to="/news" tag="button">
        news页
      </router-link>
      <router-link to="/about" tag="button">
        关于我们页
      </router-link>

    </div>
    
    <router-view></router-view>
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // home news about
    const Home = {
      template: `
        <div>
          <h1>home页</h1>
        </div>
      `,
      mounted(){
       // console.log(this.$router)
      }
    }
    const News = {
      template: `
        <div>
          <h1>新闻页</h1>
          
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h1>关于我们</h1>
        </div>
      `
    }
    const NotFound = {
      template: `
        <div>
          <h1>404</h1>
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <button @click="login">登录</button>
        </div>
      `,
      mounted(){
        console.log(this.$route)
      },
      methods:{
        login(){
          // 返回token
         setTimeout(()=>{
          localStorage.setItem('access_token','dwhidjwijdwio');
          console.log(this.$route.params.from)
          if(this.$route.params.from){
            // 从哪里重定向过来的 就跳转到哪里去
            this.$router.push(this.$route.params.from)
          }else{
            this.$router.push('/home')
          }
         },1000)
        }
      }
    }
    const routes = [ // 定义路由 规则 有哪些路由，这个路由对于的组件是什么
      {
        path: '/',
        redirect: '/home' // 重定向
      },
      {
        path:"/login",
        name:"login",
       
        component:Login
      },
      {
        path: "/home",
      
        component: Home
      },
      {
        path: "/news",
        props:true,
       
        component: News
      },
      {
        path: '/about',
        beforeEnter(to,from,next){
          const token = localStorage.getItem('access_token');
          if(token){
            next();
          }else{
            next('/login');
          }
          
        },
        component: About
      },
      {
        path: "*",
        component: NotFound
      }
    ]
    // 定义路由对象
    const router = new VueRouter({
      routes
    })
    
    const vm = new Vue({
      el: "#app",
      router
    })
  </script>
</body>

</html>
